import { useEffect, useState } from "react";
import { connect } from 'umi';
import { Table, Space, Button, Alert, Form, Tabs, Modal, Input, Tree, Row, Col, Empty, message, Spin } from 'antd';
import styles from './style.less'
import { LockOutlined, MenuOutlined } from "@ant-design/icons";
import TextButton from '@/components/TextButton'
import ArrayUtils from "@/utils/ArrayUtils";
import { saveEnterpriseRole, deleteEnterpriseRole } from '@/services/enterprise'
import { saveRolePermission } from '@/services/permision';

const FormItem = Form.Item;

const { TabPane } = Tabs;

const baseColumns = [{
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    render: (text, record, index) => `${index + 1}`
},
{
    title: '角色名',
    dataIndex: 'name',
    key: 'name',
}]


const EnterpriseRole = (props) => {

    const {
        dispatch,
        enterpriseRoleList = [],
        projectRoleList = [],
        loadingEnterpriseRole,
        permissionTree,
        rolePermission,
        permissionTreeLoading,
        projectPermissonTree
    } = props;

    const [tabKey, setTabKey] = useState('role')
    const [initRoleData, setInitRoleData] = useState({})
    const [roleSaveModalVisible, setRoleSaveModalVisible] = useState(false);
    const [form] = Form.useForm();
    const [selectRole, setSelectRole] = useState();
    const [selectPermissionCode, setSelectPermissionCode] = useState({})

    const addRoleButton = () => {

        return (
            <div className={styles.addRoleButton}>
                <div>操作</div>
                <a size="small" type="link" onClick={() => {
                    setRoleSaveModalVisible(true)
                }}>新增角色</a>
            </div>
        )
    }
    const actionColumns = [{
        title: (<> {addRoleButton()} </>),
        key: 'action',
        width: '24%',
        render: (text, record) => {
            return (
                <div className={styles.actionClass}>
                    {!isTemplateRole(record) &&
                        (<>
                            <TextButton onClick={() => {
                                console.log(record)
                                setInitRoleData(record);
                                setRoleSaveModalVisible(true);
                            }}>修改</TextButton>
                            <TextButton
                                type="danger"
                                onClick={() => {
                                    deleteRole(record)
                                }}>删除</TextButton>
                        </>)}
                </div>
            )
        },
    }]

    useEffect(() => {
        form.resetFields()
    }, [initRoleData])

    useEffect(() => {
        setSelectPermissionCode({
            checked: rolePermission
        })
    }, [rolePermission])

    useEffect(() => {
        dispatchRoleList();
    }, [tabKey])

    useEffect(() => {
        dispatch({
            type: 'permission/listEnterprisePermission',
        })
        dispatch({
            type: 'permission/listEnterpriseProjectPermission',
        })
    }, [])


    const filterColumns = (baseColumns) => {
        return [...baseColumns, ...actionColumns];
    }

    const saveRole = async () => {
        const values = await form.validateFields();
        console.log(values);
        console.log(tabKey)
        saveEnterpriseRole({
            ...values,
            scope: tabKey === "role" ? "enterprise" : "project",
        }).then((success) => {
            if (success) {
                dispatchRoleList();
                hideRoleSaveModal();
            }
        })

    }

    const deleteRole = (role) => {
        let content = `确认删除角色：${role.name}`;
        if (role.scope === 'PROJECT') {
            content =
                (< >
                    <div style={{
                        paddingLeft: '8px',
                        paddingBottom: '8px',
                    }}>
                        {content}
                    </div>
                    <Alert showIcon message="角色删除之后，项目成员角色为该角色的成员将不能使用！" type="warning" />
                </>)
        }
        Modal.confirm({
            title: '删除角色',
            content: content,
            okText: '确认',
            cancelText: '取消',
            onOk: (v) => {
                deleteEnterpriseRole({
                    ...role
                }).then(({ success }) => {
                    if (success) {
                        dispatchRoleList(role.scope);
                    }
                })
                return Promise.resolve()
            }
        });

    }



    const saveSelectPermission = () => {
        saveRolePermission(selectRole.id, {
            codes:selectPermissionCode.checked
        })
            .then((success) => {
                if (success) {
                    message.success("保存成功！")
                }
            })
    }

    const isTemplateRole = (role) => {
        return role.code !== "";
    }

    const onTabChange = (key) => {
        setTabKey(key);
    };

    const dispatchRoleList = (roleScope) => {
        let scope = roleScope || ((tabKey === 'role') ? "ENTERPRISE" : "PROJECT")
        // console.log("dispatchRoleList", scope)
        if (scope === 'ENTERPRISE') {
            dispatch({
                type: 'enterprise/listEnterpriseRole',
            })

        }
        if (scope === 'PROJECT') {
            dispatch({
                type: 'enterprise/listProjectRole',
            })
        }
    }

    if (!enterpriseRoleList) {
        return ''
    }


    const permissionTitleRender = (record) => {
        if (record.type === 1) {
            return (<div><MenuOutlined /> {record.title}</div>)
        } else {
            return (<div><LockOutlined />{record.title}</div>)
        }
    }

    const mapChildrenPermission = (children) => {
        let checked = [];
        for (const index in children) {
            checked.push(children[index].key)
            if (children[index].children && children[index].children.length > 0) {
                checked.push(...mapChildrenPermission(children[index].children));
            }
        }
        return checked;
    }
    const onClickRole = (role) => {
        setSelectRole(role)
        dispatch({
            type: 'permission/listRolePermission',
            payload: {
                roleId: role.id
            }
        })
    }

    const onCheckPermssioon = (selectedKeys, event) => {

        let checked = []
        if (event.node.children && event.node.children.length > 0) {
            checked.push(...mapChildrenPermission(event.node.children));
        }
        if (event.checked) {
            // 子节点都选上
            let parentKey = event.node.keyPath ? event.node.keyPath.split("-") : [];
            selectedKeys.checked.push(...checked)
            selectedKeys.checked.push(...parentKey)
        } else {
            // 子节点都去除
            ArrayUtils.removeAll(selectedKeys.checked, checked)
        }
        selectedKeys.checked = ArrayUtils.unique(selectedKeys.checked)
        setSelectPermissionCode(selectedKeys)
    }

    const hideRoleSaveModal = async () => {
        await setInitRoleData({})
        form.resetFields();
        setRoleSaveModalVisible(false);
    }

    return (<div className={styles.roleManage}>
        <Tabs className={styles.roleTabs} onChange={onTabChange}>
            <TabPane tab="企业角色" key="role">
                <Table
                    loading={loadingEnterpriseRole}
                    columns={filterColumns(baseColumns)}
                    dataSource={enterpriseRoleList}
                    pagination={false}
                    rowKey="id"
                    rowClassName={(record, index) => {
                        return record?.id === selectRole?.id ? styles.selectRow : ""
                    }}
                    size="small"
                    onRow={record => {
                        return {
                            onClick: () => {
                                onClickRole(record)
                            },
                        };
                    }}
                    bordered>
                </Table>
            </TabPane>
            <TabPane tab="项目角色" key="projectRole">
                <Table
                    loading={loadingEnterpriseRole}
                    dataSource={projectRoleList}
                    rowKey="id"
                    rowClassName={(record, index) => {
                        return record?.id === selectRole?.id ? styles.selectRow : ""
                    }}
                    columns={filterColumns(baseColumns)}
                    pagination={false}
                    onRow={record => {
                        return {
                            onClick: () => onClickRole(record),
                        };
                    }}
                    size="small"
                    bordered>
                </Table>
            </TabPane>
        </Tabs>
        {selectRole ?
            <div className={styles.rolePermission}>
                <div className={styles.roleTitleClass}>
                    {selectRole.scope === "PROJECT" ? "项目角色" : "企业角色"} / {selectRole.name}
                </div>
                <Spin spinning={permissionTreeLoading}>
                    <Row align="top" justify="start" >
                        {
                            (selectRole.scope === "PROJECT" ? projectPermissonTree : permissionTree).map(item => {
                                return (
                                    <Col className={styles.treeNodeClass} key={item.key} span={{ xs: 12, sm: 8, md: 8, lg: 6 }}>
                                        <Tree
                                            loading={permissionTreeLoading}
                                            checkable={selectRole.code != "ADMIN"}
                                            defaultExpandAll={true}
                                            onCheck={(selectedKeys, event) => {
                                                console.log(selectedKeys, event)
                                                onCheckPermssioon(selectedKeys, event)
                                            }}
                                            checkStrictly={true}
                                            treeData={[item]}
                                            titleRender={permissionTitleRender}
                                            checkedKeys={selectPermissionCode}
                                        >
                                        </Tree>
                                    </Col>
                                )
                            })
                        }
                    </Row>
                </Spin>
                <div>
                    {selectRole.code != "ADMIN"
                        &&
                        <Button type="primary" onClick={saveSelectPermission}>保存</Button>
                    }
                </div>
            </div>
            :
            <div className={styles.roleEmptyPermission}>
                <Empty
                    description="单击角色查看权限"
                />
            </div>

        }

        <Modal
            visible={roleSaveModalVisible}
            closable
            title={initRoleData.id ? "修改角色" : "新增角色"}
            onCancel={() => {
                hideRoleSaveModal()
            }}
            destroyOnClose
            onOk={saveRole}
        >
            <Form
                form={form}
                initialValues={initRoleData}
            >
                <FormItem
                    label="ID"
                    name="id"
                    hidden={true}
                >
                </FormItem>
                <FormItem
                    label="角色名称"
                    name="name"
                    rules={[
                        {
                            required: true,
                            message: "请填入角色名称",
                        },
                    ]}
                >
                    <Input
                        placeholder="角色名称"
                    />
                </FormItem>
            </Form>
        </Modal>
    </div>)
}

const mapPermission = (permission, parentPath) => {
    let keyPath = parentPath ? (parentPath + '-' + permission.code) : permission.code
    let children = permission.subPermissionList ? permission.subPermissionList.map(sub => mapPermission(sub, keyPath)) : []
    return {
        title: permission.name,
        key: permission.code,
        type: permission.type,
        keyPath: parentPath,
        children: children
    }
}

const mappedToStates = ({ enterprise, loading, permission }) => {
    let permissionTree = [];
    let projectPermissonTree = []
    if (permission.enteprisePermission) {
        permissionTree = permission.enteprisePermission.map(permission => {
            return mapPermission(permission)
        })
    }
    if (permission.entepriseProjectPermission) {
        projectPermissonTree = permission.entepriseProjectPermission.map(permission => {
            return mapPermission(permission)
        })
    }
    return {
        loadingEnterpriseRole: loading.effects['enterprise/listEnterpriseRole'],
        enterpriseRoleList: enterprise.enterpriseRoleList,
        projectRoleList: enterprise.projectRoleList,
        permissionTree: permissionTree,
        projectPermissonTree: projectPermissonTree,
        rolePermission: permission.rolePermission,
        permissionTreeLoading: loading.effects['permission/listRolePermission']
    }
}

export default connect(mappedToStates)(EnterpriseRole);